import java.io.FileOutputStream;
import java.io.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Product> products = new ArrayList<>();
        File file = new File("records.txt");

        try {
            // 写入进货记录
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            ObjectOutputStream oos = new ObjectOutputStream(bos);

            // 读取进货记录
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            ObjectInputStream ois = new ObjectInputStream(bis);

            // 读取产品信息
            while (fis.available() > 0) {
                Product product = (Product) ois.readObject();
                products.add(product);
            }

            // 写入新的产品信息
            Product newProduct = new Product("iPhone 12", 100, 7999.0, LocalDate.now(), null);
            products.add(newProduct);
            oos.writeObject(products);

            // 计算总进货金额、销售金额和利润
            double totalPurchaseAmount = products.stream()
                    .mapToDouble(p -> p.getQuantity() * p.getPrice())
                    .sum();

            double totalSaleAmount = products.stream()
                    .filter(p -> p.getSaleDate() != null)
                    .mapToDouble(p -> p.getQuantity() * p.getPrice())
                    .sum();

            double profit = totalSaleAmount - totalPurchaseAmount;

            // 关闭数据流
            oos.close();
            ois.close();
        } catch (IOException e) {
            // 处理IOException异常
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // 处理ClassNotFoundException异常
            e.printStackTrace();
        }
    }
}
